/**
 * 体优一体化局点定制逻辑
 */
window.CustomerDiy = {

  // 多值组件点击重复发送事件: 默认undefined和true均重复发送事件，false不重复发送事件
  sameEvtResend: false,

  // 转换百分比
  _permil(num, decimalCount) {
    let _str = `${num}`;
    const reg = /\d{1,3}(?=(\d{3})+$)/g;
    _str = _str.replace(/([^\d\.,]?)(\d+)((\.\d+)?)/g, (s, s1, s2, s3) => {
      let tail = s3;
      if (decimalCount) {
        tail = Number(`0${s3}`)
          .toFixed(decimalCount)
          .slice(1);
      }
      return s1 + s2.replace(reg, '$&,') + tail;
    });
    return _str;
  },

  _convertToPercent(val) {
    let num = parseFloat(val);
    if (isNaN(num)) {
      return val; // 转换失败，返回原值
    } else {
      num = `${this._permil(num * 100, 2)}%`;
      return num; // 转换成功，返回数字
    }
  },

  // 多值组件处理数据
  formatApiData(data, comp) {
    const { tableData } = comp.config.config.data;
    const propertyData = comp.config.config.property.data;
    if (!data.length) {
      return data;
    }

    const keysMap = {};
    tableData.forEach(n => {
      keysMap[n.mapping] = n.field; // 对照： NNPS_GRP_SIM_IND_POOR_USER_COUNT： y
    });

    const newData = [];
    const keys = Object.keys(keysMap);
    let needFormat = false;
    keys.forEach(key => {
      if (!key.includes('NNPS_GRP_SIM_IND_')) {
        return true;
      }
      let _key = key.replace('NNPS_GRP_SIM_IND_', '');
      _key = `${_key}_RATE`;

      if (!keys.includes(_key)) {
        return true;
      }

      const y1 = this._convertToPercent(data[0][keysMap[_key]]); // 环比转换为百分比形式
      const propertyIt = propertyData.find(n => n.name === key);

      const item = {
        s: key,
        y: data[0][keysMap[key]],
        y1,
        unit: propertyIt?.unit || '',
        y2: propertyIt?.alias || '',
      };
      newData.push(item);
      needFormat = true;
      return true;
    });

    if (!needFormat) {
      return data;
    }

    comp.isDataAbnormal = false;
    return newData;
  },
};
